﻿using EasyMirai.MiraiJar;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace EasyMirai
{
    public class MiraiFiles:IDisposable
    {
        private List<MiraiJAR> MiraiJAR = new List<MiraiJAR>();
        private readonly string[] miraiFiles = new string[] { "mirai-console", "mirai-console-pure", "mirai-core-qqandroid" };
        private RichTextBox logbox;
        public bool Downloading { get; private set; }
        public MiraiFiles(RichTextBox logbox)
        {
            this.logbox = logbox;
            AddLog("正在检查更新...");
            foreach(var file in miraiFiles)
            {
                MiraiJAR.Add(new MiraiJAR(file, "mamoe", true));
            }
            MiraiJAR.Add(new MiraiJAR("mirai-native", "iTXTech"));
            MiraiJAR.Add(new MiraiJAR("mirai-api-http", "project-mirai"));
        }

        public bool FileCheck()
        {
            var files = Directory.GetFiles(Environment.CurrentDirectory, "*.jar", SearchOption.AllDirectories);
            bool existsAll = true;
            foreach(var file in MiraiJAR)
            {
                bool fileExist = false;
                foreach(var current in files)
                {
                    if (current.Contains(file.FileName))
                    {
                        if (file.NewestCheck(current))
                        {
                            //file exist
                            fileExist = true;
                            break;
                        }
                    }
                }
                if (!fileExist)
                {
                    existsAll = false;
                }
            }
            return existsAll;
        }

        public async void DownloadFiles()
        {
            Downloading = true;
            AddLog("请勿关闭此窗口！正在下载更新！",Color.Yellow);
            foreach (var file in MiraiJAR)
            {
                AddLog("正在下载 " + file.DownloadUrl);
                file.Download();
                do
                {
                    await Task.Delay(1000);
                }
                while (file.DownloadingFile);
                AddLog("下载成功！");
            }
            Downloading = false;
        }
        private void AddLog(string log, Color color = default)
        {
            logbox.Invoke((MethodInvoker)delegate
            {
                if (color != default)
                {
                    logbox.SelectionStart = logbox.TextLength;
                    logbox.SelectionLength = 0;
                    logbox.SelectionColor = color;
                }
                logbox.AppendText(log + Environment.NewLine);
                logbox.SelectionColor = logbox.ForeColor;
            });
        }

        public void Dispose()
        {
           foreach(var jar in MiraiJAR)
            {
                jar.Dispose();
            }
        }
    }
}
